#!/usr/bin/env bash

# input variables:
#  GIT_BRANCH
#  GIT_COMMIT
#  BUILD_NUMBER
#  BUILDING_PRODUCT (ex: "rec" or "auth")

# eat origin/ off branch name
GIT_BRANCH=${GIT_BRANCH#origin/}
date=$(date +%Y%m%d)
git_id=$(git rev-parse --short $GIT_COMMIT)
source_branch="$(echo ${GIT_BRANCH} | tr ' /' -)"
deb_branch="$(echo ${GIT_BRANCH} | tr ' /-' .)"
rpm_branch="$(echo ${GIT_BRANCH} | tr ' /-' _)"
# dbg: date, build, gitid
source_dbg=${date}-${BUILD_NUMBER}-${git_id}
deb_dbg=${date}.${BUILD_NUMBER}.${git_id}
rpm_dbg=${date}_${BUILD_NUMBER}_${git_id}

is_release_build=0

if [ $GIT_BRANCH = master ]
then
	source_version=git-${source_dbg}
	deb_version=0.0.${deb_dbg}
	rpm_version=0.0.${rpm_dbg}
elif [[ $GIT_BRANCH = rel/* ]] || [ $PDNS_TAG != HEAD ]
then
	# on release branch or doing a release
	if [[ $PDNS_TAG = $BUILDING_PRODUCT-* ]]
	then
		product_version=${PDNS_TAG}
		product=$BUILDING_PRODUCT
	else
		product_version=${GIT_BRANCH#rel/}
		product=${product_version%-*} # ex: "rec" or "auth"
	fi
	version=${product_version#*-} # ex: "3.5.1"
	if [ "$product" = "$BUILDING_PRODUCT" ]
	then
		expected_tag=${product}-${version} # ex: "rec-3.5.1"
		git_tag=$(git describe --exact-match --match "${expected_tag}*" 2>/dev/null)
		if [ -z "$git_tag" ]
		then
			# snapshot build:
			# prepend the target product version.
			source_version=${version}-snapshot-${date}-${BUILD_NUMBER}-${git_id}
			deb_version=${version}~snapshot${date}.${BUILD_NUMBER}.${git_id}
			rpm_version=${version}snapshot${date}_${BUILD_NUMBER}_${git_id}
		else
			# rcX or release build:
			# use the tag as the real version number.
			source_version=${git_tag#${product}-}
			deb_version=${source_version}
			rpm_version="$(echo ${source_version} | sed -e 's/-//' )"
			is_release_build=1
                fi
        else
                # building auth on recursor release branch, or v.v.
		source_version=git-unknown-${source_dbg}
		deb_version=0.0~unknown.${deb_dbg}
		rpm_version=0.0unknown_${rpm_dbg}
        fi
else
        # must be a test branch
        source_version=git-${source_branch}-${source_dbg}
	deb_version=0.0~${deb_branch}.${deb_dbg}
	rpm_version=0.0.${rpm_branch}_${rpm_dbg}
fi

echo SOURCE_VERSION=$source_version
echo DEB_VERSION=$deb_version
echo RPM_VERSION=$rpm_version
echo IS_RELEASE_BUILD=$is_release_build
